package middlewareLogExtraction.model;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import middlewareLogExtraction.model.exception.InvalidLogFileException;

public class DB2LogBuilder {
	private final String fileNamePattern = ".*\\/mw.ui(\\d)*\\/rpt\\/middleware\\.log\\.\\d{14}(.gz)?(.gzip)?(.Z)?$";

	private final GzipHelper helper;
	
	public DB2LogBuilder(GzipHelper helper){
		this.helper = helper;
	}
	
	public DB2Log getLog(final String logFileName, RegexHelper regexHelper) throws InvalidLogFileException, IOException, FileNotFoundException{
		Pattern pattern = Pattern.compile(fileNamePattern);
		Matcher matcher = pattern.matcher(logFileName);
		if(!matcher.matches()){
			throw new InvalidLogFileException();
		}
		if(isFileZipped(logFileName)){
			extractFile(logFileName, getExtractedFileName(logFileName));
			return new DB2Log(getExtractedFileName(logFileName), regexHelper);
		}
		return new DB2Log(logFileName, regexHelper);
	}

	private boolean isFileZipped(String fileName){
		if(fileName.endsWith(".gzip") || 
				fileName.endsWith(".Z") ||
				fileName.endsWith(".gz"))
			return true;
		else
			return false;
	}
	
	private void extractFile(String zipFileName, String extractedFileName) throws IOException {
		this.helper.extract(zipFileName, extractedFileName);
	}
	
	private String getExtractedFileName(String logFileName){
		return logFileName+".ext";
	}
}
